package com.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.blog.mapper.ArticleMapper;
import com.blog.pojo.CacheProperties;
import com.blog.service.ArticleService;
import com.blog.pojo.Article;
import com.blog.service.IndexService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private IndexService indexService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void addArticle(Article article) {
        Date date = new Date();
        article.setCreateDate(date);
        article.setUpdateDate(date);
        articleMapper.addArticle(article);

    }

    @Override
    public List<Article> list(int limit,int offset) {
        List<Article> articles = indexService.pageArticles(offset, limit);
        return articles;
    }

    @Override
    public Long count() {

        return indexService.count();
    }

    @Override
    public Article detail(int id) {
        String json = (String) redisTemplate.boundValueOps(CacheProperties.PRE_ARTICLE_KEY + id).get();
        if (StringUtils.isEmpty(json)){
            if (redisTemplate.opsForValue().setIfAbsent(CacheProperties.PRE_ARTICLE_LOCK+id,"",3, TimeUnit.SECONDS)) {
                Article article = articleMapper.detail(id);
                String jsonString = JSON.toJSONString(article);
                redisTemplate.boundValueOps(CacheProperties.PRE_ARTICLE_KEY+id).set(jsonString,1,TimeUnit.HOURS);
                return article;
            }else {
                throw new RuntimeException();
            }
        }else {
            Article article = JSON.parseObject(json, Article.class);
            return article;
        }
    }

    @Override
    public void edit(Article article) {
        articleMapper.edit(article);
        HashMap<String, Object> map = new HashMap<>();
        map.put("type","update");
        map.put("article",article);
        rabbitTemplate.convertAndSend("ESExchange","es",map);
    }

    @Override
    public void delete(int id) {
        articleMapper.delete(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("type","delete");
        map.put("id",id);
        rabbitTemplate.convertAndSend("ESExchange","es",map);
    }


}
